import axios from 'axios'
import { MessageBox, Message } from 'element-ui'

// 实例化 axios
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  timeout: 10000 // 请求超时时间
})
service.jsonp = (url, data,callback)=> {
  return new Promise((resolve, reject) => {
    if (!url) {
      reject("url不能为空");
    } else {
      const JSONP = document.createElement("script");
      JSONP.setAttribute("type", "text/javascript");

      const headEle = document.getElementsByTagName("head")[0];

      let ret = "";
      if (data) {
        if (typeof data === "string") ret = "&" + data;
        else if (typeof data === "object") {
          for (let key in data)
            ret += "&" + key + "=" + encodeURIComponent(data[key]);
        }
        ret += "&_time=" + Date.now();
      }
      //callback=${callback}
      JSONP.src = `${url}?callback=${callback}${ret}`;

      window[callback] = function (r) {
        resolve(r)
        headEle.removeChild(JSONP);
        delete window[callback];
      };

      headEle.appendChild(JSONP);
    }
  });
}

// 响应拦截
service.interceptors.response.use(
  response => {
    const res = response.data
    // if the custom code is not 20000, it is judged as an error.
    if (res.code !== 200) {
      Message({
        message: res.msg || 'Error',
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject(new Error(res.msg || 'Error'))
    } else {
      return res
    }
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: '网络错误' || error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
